/*
 * Copyright (c) 2017-present, CV4J Contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.cv4j.core.filters;

import com.cv4j.core.datamodel.ImageProcessor;
import com.cv4j.image.util.Tools;

import java.util.Optional;

/**
 * 乌贼语气过滤器
 *
 * @author dev
 * @date 2021/07/22
 */
public class SepiaToneFilter extends BaseFilter {
    /**
     * 做的过滤器
     *
     * @param src src
     * @return {@link Optional<ImageProcessor>}
     */
    @Override
    public Optional<ImageProcessor> doFilter(ImageProcessor src) {
        int total = width * height;
        int r1 = 0;
        int g1 = 0;
        int b1 = 0;
        for (int i = 0; i < total; i++) {
            r1 = RED[i] & 0xff;
            g1 = GREED[i] & 0xff;
            b1 = BLUE[i] & 0xff;

            r1 = (int) colorBlend(noise(), (r1 * 0.393) + (g1 * 0.769) + (b1 * 0.189), r1);
            g1 = (int) colorBlend(noise(), (r1 * 0.349) + (g1 * 0.686) + (b1 * 0.168), g1);
            b1 = (int) colorBlend(noise(), (r1 * 0.272) + (g1 * 0.534) + (b1 * 0.131), b1);

            RED[i] = (byte) Tools.clamp(r1);
            GREED[i] = (byte) Tools.clamp(g1);
            BLUE[i] = (byte) Tools.clamp(b1);
        }
        return Optional.ofNullable(src);
    }

    /**
     * 噪音
     *
     * @return double
     */
    private double noise() {
        return Math.random() * 0.5 + 0.5;
    }

    /**
     * 颜色混合
     *
     * @param scale 规模
     * @param dest 桌子
     * @param src src
     * @return double
     */
    private double colorBlend(double scale, double dest, double src) {
        return (scale * dest + (1.0 - scale) * src);
    }
}
